/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.sdkj.dspservice.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.TimeZone;

/**
 * 简单封装Jackson，实现JSON String<->Java Object的Mapper.
 * 封装不同的输出风格, 使用不同的builder函数创建实例.
 * @author ThinkGem
 * @version 2013-11-15
 */
public class JsonUtils extends ObjectMapper {

	private static final long serialVersionUID = 1L;

	private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);

	private static JsonUtils jsonUtils;

	public JsonUtils() {
		this(Include.NON_EMPTY);
	}

	public JsonUtils(Include include) {
		// 设置输出时包含属性的风格
		if (include != null) {
			this.setSerializationInclusion(include);
		}
		// 允许单引号、允许不带引号的字段名称
		this.enableSimple();
		// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
		this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // 空值处理为空串
		this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>(){
			@Override
			public void serialize(Object value, JsonGenerator jgen,
					SerializerProvider provider) throws IOException,
					JsonProcessingException {
				jgen.writeString("");
			}
        });
		// 进行HTML解码。
		this.registerModule(new SimpleModule().addSerializer(String.class, new JsonSerializer<String>(){
			@Override
			public void serialize(String value, JsonGenerator jgen,
					SerializerProvider provider) throws IOException,
					JsonProcessingException {
				jgen.writeString(StringEscapeUtils.unescapeHtml4(value));
			}
        }));
		// 设置时区，getTimeZone("GMT+8:00")
		this.setTimeZone(TimeZone.getDefault());
	}

	/**
	 * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
	 */
	public static JsonUtils getInstance() {
		if (jsonUtils == null){
			jsonUtils = new JsonUtils().enableSimple();
		}
		return jsonUtils;
	}

	/**
	 * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式，建议在内部接口中使用。
	 */
	public static JsonUtils nonDefaultMapper() {
		if (jsonUtils == null){
			jsonUtils = new JsonUtils(Include.NON_DEFAULT);
		}
		return jsonUtils;
	}
	
	/**
	 * Object可以是POJO，也可以是Collection或数组。
	 * 如果对象为Null, 返回"null".
	 * 如果集合为空集合, 返回"[]".
	 */
	public String toJson(Object object) {
		try {
			return this.writeValueAsString(object);
		} catch (IOException e) {
			logger.warn("write to json string error:" + object, e);
			return null;
		}
	}

	/**
	 * 反序列化POJO或简单Collection如List<String>.
	 * 
	 * 如果JSON字符串为Null或"null"字符串, 返回Null.
	 * 如果JSON字符串为"[]", 返回空集合.
	 * 
	 * 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType)
	 * @see #fromJson(String, JavaType)
	 */
	public <T> T fromJson(String jsonString, Class<T> clazz) {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}
		try {
			return this.readValue(jsonString, clazz);
		} catch (IOException e) {
			logger.warn("parse json string error:" + jsonString, e);
			return null;
		}
	}

	/**
	 * 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调用本函数.
	 * @see #createCollectionType(Class, Class...)
	 */
	@SuppressWarnings("unchecked")
	public <T> T fromJson(String jsonString, JavaType javaType) {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}
		try {
			return (T) this.readValue(jsonString, javaType);
		} catch (IOException e) {
			logger.warn("parse json string error:" + jsonString, e);
			return null;
		}
	}

	/**
	 * 構造泛型的Collection Type如:
	 * ArrayList<MyBean>, 则调用constructCollectionType(ArrayList.class,MyBean.class)
	 * HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class)
	 */
	public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
		return this.getTypeFactory().constructParametricType(collectionClass, elementClasses);
	}

	/**
	 * 當JSON裡只含有Bean的部分屬性時，更新一個已存在Bean，只覆蓋該部分的屬性.
	 */
	@SuppressWarnings("unchecked")
	public <T> T update(String jsonString, T object) {
		try {
			return (T) this.readerForUpdating(object).readValue(jsonString);
		} catch (JsonProcessingException e) {
			logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
		} catch (IOException e) {
			logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
		}
		return null;
	}

	/**
	 * 輸出JSONP格式數據.
	 */
	public String toJsonP(String functionName, Object object) {
		return toJson(new JSONPObject(functionName, object));
	}

	/**
	 * 設定是否使用Enum的toString函數來讀寫Enum,
	 * 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
	 * 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
	 */
	public JsonUtils enableEnumUseToString() {
		this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
		this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
		return this;
	}

	/**
	 * 支持使用Jaxb的Annotation，使得POJO上的annotation不用与Jackson耦合。
	 * 默认会先查找jaxb的annotation，如果找不到再找jackson的。
	 */
	public JsonUtils enableJaxbAnnotation() {
		JaxbAnnotationModule module = new JaxbAnnotationModule();
		this.registerModule(module);
		return this;
	}

	/**
	 * 允许单引号
	 * 允许不带引号的字段名称
	 */
	public JsonUtils enableSimple() {
		this.configure(Feature.ALLOW_SINGLE_QUOTES, true);
		this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
		return this;
	}
	
	/**
	 * 取出Mapper做进一步的设置或使用其他序列化API.
	 */
	public ObjectMapper getMapper() {
		return this;
	}

	/**
	 * 对象转换为JSON字符串
	 * @param object
	 * @return
	 */
	public static String toJsonString(Object object){
		return JsonUtils.getInstance().toJson(object);
	}
	
	/**
	 * JSON字符串转换为对象
	 * @param jsonString
	 * @param clazz
	 * @return
	 */
	public static Object fromJsonString(String jsonString, Class<?> clazz){
		return JsonUtils.getInstance().fromJson(jsonString, clazz);
	}

	/**
	 * 根据key获取值
	 * @param jsonNode
	 * @param key 以-分割
	 * @return
	 * @throws Exception
	 */
	public static String getValue(JsonNode jsonNode, String key){
		String result = "";
		if(jsonNode.has(key)){
			JsonNode node = jsonNode.get(key);
			if(node != null){
				result = node.asText();
			}
		}
		return result;
	}

	/**
	 * 根据key获取值
	 * @param jsonString
	 * @param key 以-分割
	 * @return
	 * @throws Exception
	 */
	public static String getValue(String jsonString, String key){
		return getJsonNode(jsonString, key).asText().replaceAll("\"", "");
	}

	/**
	 * 根据key获取值
	 * @param jsonString
	 * @param key 以-分割
	 * @return
	 * @throws Exception
	 */
	public static JsonNode getJsonNode(String jsonString, String key){
		if(StringUtils.isBlank(jsonString) || StringUtils.isBlank(key)){
			return null;
		}
		JsonNode result = null;
		try {
			ObjectMapper mapper = new ObjectMapper();
			JsonNode rootNode = mapper.readTree(jsonString);
			String[] keys = key.split("-");
			JsonNode node = null;
			int i = 0;
			for(String k : keys){
				if(i == 0){
					node = rootNode;
				}
				if(StringUtils.isNumeric(k)){
					node = node.get(Integer.parseInt(k));
				}else {
					node = node.get(k);
				}
				i++;
			}
			result = node;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 测试
	 */
	public static void main(String[] args) {
//		List<Map<String, Object>> list = new ArrayList<>();
//		Map<String, Object> map = new HashMap<>(16);
//		map.put("id", 1);
//		map.put("pId", -1);
//		map.put("name", "根节点");
//		list.add(map);
//		map = new HashMap<>(16);
//		map.put("id", 2);
//		map.put("pId", 1);
//		map.put("name", "你好");
//		map.put("open", true);
//		list.add(map);
//		String json = JsonUtils.getInstance().toJson(list);
//		System.out.println(json);
		String s = "{\n" +
				"  \"data\": {\n" +
				"    \"version\": \"13.0.0\",\n" +
				"    \"dataCenterRoles\": [\n" +
				"      {\n" +
				"        \"id\": \"WlGk4Daj\",\n" +
				"        \"name\": \"拥有者\",\n" +
				"        \"members\": [\n" +
				"          {\n" +
				"            \"id\": \"zqQRq3Do\",\n" +
				"            \"name\": \"单沛丰\"\n" +
				"          }\n" +
				"        ]\n" +
				"      },\n" +
				"      {\n" +
				"        \"id\": \"y9pm1pme\",\n" +
				"        \"name\": \"超级管理员\",\n" +
				"        \"members\": [\n" +
				"          {\n" +
				"            \"id\": \"KzpNmzQk\",\n" +
				"            \"name\": \"曹怀\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"rRGoYQml\",\n" +
				"            \"name\": \"胡道航\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"klGvOyD7\",\n" +
				"            \"name\": \"何增强\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"rRGoyYQm\",\n" +
				"            \"name\": \"刘林希\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"qgQMnp3L\",\n" +
				"            \"name\": \"杨浚帆\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"n1QVaDyR\",\n" +
				"            \"name\": \"王晖\"\n" +
				"          }\n" +
				"        ]\n" +
				"      },\n" +
				"      {\n" +
				"        \"id\": \"n1QVaDyR\",\n" +
				"        \"name\": \"数据管理员\",\n" +
				"        \"members\": []\n" +
				"      },\n" +
				"      {\n" +
				"        \"id\": \"AbQ3bDYe\",\n" +
				"        \"name\": \"企业成员\",\n" +
				"        \"members\": [\n" +
				"          {\n" +
				"            \"id\": \"JnG44mGz\",\n" +
				"            \"name\": \"周乐平\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"zZDbbKD9\",\n" +
				"            \"name\": \"胡珍丽\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"mgGJqLpA\",\n" +
				"            \"name\": \"陈晖\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"AVpZBzpK\",\n" +
				"            \"name\": \"何英\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"WkDyZOQe\",\n" +
				"            \"name\": \"张雨\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"RqQwNPDJ\",\n" +
				"            \"name\": \"程骥\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"evp9gkDO\",\n" +
				"            \"name\": \"朱婧\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"kqQeAwQr\",\n" +
				"            \"name\": \"魏一岭\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"wWDrYwGM\",\n" +
				"            \"name\": \"黄思铭\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"n1QVqaDy\",\n" +
				"            \"name\": \"陈佰华\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"AbQ3MbGY\",\n" +
				"            \"name\": \"API对外接口\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"klGvyp7E\",\n" +
				"            \"name\": \"刘东升\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"nxGK0Da6\",\n" +
				"            \"name\": \"吴春怡\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"y9pmz1Gm\",\n" +
				"            \"name\": \"符永康\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"WlGk44Da\",\n" +
				"            \"name\": \"tydk\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"mgGJLQA4\",\n" +
				"            \"name\": \"王震寰\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"oNGzxQgB\",\n" +
				"            \"name\": \"谭涌\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"AVpZzpKy\",\n" +
				"            \"name\": \"王靓明\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"RqQwPpJw\",\n" +
				"            \"name\": \"毛芳\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"evp9kDOx\",\n" +
				"            \"name\": \"黄飞\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"JnG4mDzK\",\n" +
				"            \"name\": \"黄祖敏\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"zZDbKQ9o\",\n" +
				"            \"name\": \"罗艺\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"9yGOxDlk\",\n" +
				"            \"name\": \"测试\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"WkDyOpe4\",\n" +
				"            \"name\": \"肖剑\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"kAGP4GRM\",\n" +
				"            \"name\": \"谭麦临\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"KnGnkDRY\",\n" +
				"            \"name\": \"陈蕾丽\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"0wDaYD1E\",\n" +
				"            \"name\": \"胡欣\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"yJQA7G17\",\n" +
				"            \"name\": \"余艳清\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"3mpxwQOq\",\n" +
				"            \"name\": \"孔凡然\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"OqQjqDdR\",\n" +
				"            \"name\": \"谢晨\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"KzpNzpkv\",\n" +
				"            \"name\": \"施展\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"V0G5vDAR\",\n" +
				"            \"name\": \"赵晶\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"ExQWOQ79\",\n" +
				"            \"name\": \"黄一宇\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"qVDgrGkw\",\n" +
				"            \"name\": \"吴艳\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"NxDLNp7E\",\n" +
				"            \"name\": \"李校\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"qyD6qGKJ\",\n" +
				"            \"name\": \"肖亦非\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"nKD1PGWr\",\n" +
				"            \"name\": \"杨文杰\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"xNQXjGMb\",\n" +
				"            \"name\": \"李洁\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"bVG2Ap68\",\n" +
				"            \"name\": \"华乐\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"weDqmDEX\",\n" +
				"            \"name\": \"谢萌\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"oWpEMp6A\",\n" +
				"            \"name\": \"杨晓\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"o8D03G7P\",\n" +
				"            \"name\": \"王耔萌\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"J1GleEDj\",\n" +
				"            \"name\": \"卢晓玲\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"MvDBVDOK\",\n" +
				"            \"name\": \"叶舟\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"zqQR3po3\",\n" +
				"            \"name\": \"张济来\"\n" +
				"          },\n" +
				"          {\n" +
				"            \"id\": \"wWDrwQML\",\n" +
				"            \"name\": \"江璐\"\n" +
				"          }\n" +
				"        ]\n" +
				"      },\n" +
				"      {\n" +
				"        \"id\": \"KzpNzpkv\",\n" +
				"        \"name\": \"外部成员\",\n" +
				"        \"members\": []\n" +
				"      },\n" +
				"      {\n" +
				"        \"id\": \"oNGzxQgB\",\n" +
				"        \"name\": \"GIO 技术顾问\",\n" +
				"        \"members\": [\n" +
				"          {\n" +
				"            \"id\": \"WlGk4Daj\",\n" +
				"            \"name\": \"admin\"\n" +
				"          }\n" +
				"        ]\n" +
				"      }\n" +
				"    ]\n" +
				"  }\n" +
				"}";
		System.out.println();
	}
	
}
